package com.ezreal.ezchat.utils;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import com.ezreal.ezchat.chat.MessageListAdapter;
import com.ezreal.ezchat.utils.permission.PermissionManager;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class SecretMessage {

    public static final String SECRET_MESSAGE_TIME_KEY = "SECRET_MESSAGE_TIME_KEY";
    public static final String SECRET_MESSAGE_INDEX_KEY = "SECRET_MESSAGE_INDEX_KEY";

    private MessageListAdapter listAdapter;
    private HandlerThread handlerThread;
    private Handler handler;
    private Handler mainHandler = new Handler(Looper.getMainLooper());

    public SecretMessage(MessageListAdapter listAdapter) {
        this.listAdapter = listAdapter;
        handlerThread = new HandlerThread("SecretMessage");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper(), new CallBack());
        handler.sendEmptyMessageDelayed(0, 1000);
    }

    public void putMessage(int index, IMMessage imMessage) {
        if (!PermissionManager.getInstance().getSecretMsg()) {
            return;
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put(SECRET_MESSAGE_TIME_KEY, "10");
        map.put(SECRET_MESSAGE_INDEX_KEY, index);
        imMessage.setLocalExtension(map);
        Message message = Message.obtain();
        message.what = 1;
        message.obj = imMessage;
        handler.sendMessage(message);
    }

    private class CallBack implements Handler.Callback {

        private Map<String, IMMessage> messageArrayMap = new HashMap<>();

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    del();
                    handler.sendEmptyMessageDelayed(0, 1500);
                    break;
                case 1:
                    IMMessage imMessage = (IMMessage) msg.obj;
                    messageArrayMap.put(imMessage.getUuid(), imMessage);
                    break;
                default:
                    break;
            }
            return true;
        }

        private void del() {
            if (messageArrayMap.isEmpty()) {
                return;
            }
            Iterator<IMMessage> messageIterator = messageArrayMap.values().iterator();
            while (messageIterator.hasNext()) {
                IMMessage imMessage = messageIterator.next();
                String time = (String) imMessage.getLocalExtension().get(SECRET_MESSAGE_TIME_KEY);
                int value = Integer.valueOf(time) - 1;
                int index = (int) imMessage.getLocalExtension().get(SECRET_MESSAGE_INDEX_KEY);
                Map<String, Object> map = new HashMap<>(2);
                map.put(SECRET_MESSAGE_TIME_KEY, String.valueOf(value));
                map.put(SECRET_MESSAGE_INDEX_KEY, index);
                imMessage.setLocalExtension(map);
                if (value < 0) {
                    messageIterator.remove();
                    deleteItem(imMessage);
                } else {
                    updateItem(imMessage);
                }
            }
        }

        public void updateItem(final IMMessage imMessage) {
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    int index = (int) imMessage.getLocalExtension().get(SECRET_MESSAGE_INDEX_KEY);
                    for (int i = 0; i < listAdapter.getmMessageList().size(); i++) {
                        IMMessage listMessage = listAdapter.getmMessageList().get(i);
                        if (imMessage.getUuid().equals(listMessage.getUuid())) {
                            listAdapter.getmMessageList().set(i, imMessage);
                            listAdapter.notifyItemChanged(index);
                        }
                    }
                }
            });
        }

        public void deleteItem(final IMMessage message) {
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    int index = (int) message.getLocalExtension().get(SECRET_MESSAGE_INDEX_KEY);
                    for (int i = 0; i < listAdapter.getmMessageList().size(); i++) {
                        IMMessage listMessage = listAdapter.getmMessageList().get(i);
                        if (message.getUuid().equals(listMessage.getUuid())) {
                            listAdapter.getmMessageList().remove(i);
                            listAdapter.notifyItemRemoved(index);
                            NIMClient.getService(MsgService.class).deleteChattingHistory(message);
                        }
                    }
                }
            });
        }
    }
}
